<template>
  <div class="pb-[24px] page-goods">
    <div class="bg-[#fff] pt-[24px]">
      <div class="m-auto w">
        <div class="text-[18px] font-[400] text-[#313131]">
          <div v-if="goodsLoading">
            <n-skeleton text :repeat="2" />
          </div>
          <div v-else>{{ goods.subjectTrans }}</div>
        </div>

        <div class="flex gap-[16px] mt-[24px] relative">
          <div class="w-[560px]" ref="containerRef">
            <div class="sticky top-[90px] pb-[16px]">
              <div
                class="rounded-[8px] overflow-hidden text-0 w-[560px] h-[560px] bg-[#fff] relative"
              >
                <n-skeleton v-if="goodsLoading" height="100%" width="100%" />
                <template v-else>
                  <video
                    v-if="videoUrl"
                    :src="goods.mainVideo"
                    controls
                    width="100%"
                    height="100%"
                    :poster="cover"
                  ></video>
                  <img v-else class="object-contain w-full h-full" :src="cover" />
                  <n-popover class="black-popover" trigger="hover" placement="bottom" raw>
                    <template #trigger>
                      <div class="float-wrapper" @click.stop="onClickSimilar">
                        <n-spin v-if="uploading" size="small"> </n-spin>
                        <n-icon v-else :size="24" class="pl-[2px]">
                          <ImageSearchAlt></ImageSearchAlt>
                        </n-icon>
                      </div>
                    </template>
                    <div class="tips">
                      {{ $t("tips.以图搜图") }}
                    </div>
                  </n-popover>
                </template>
              </div>
              <div class="flex w-full h-[80px] items-center mt-[16px]">
                <div class="flex-1 w-0 thumbnail-wrapper" v-if="!goodsLoading">
                  <n-carousel
                    :slides-per-view="6"
                    :space-between="16"
                    :loop="false"
                    draggable
                  >
                    <div
                      v-if="goods.mainVideo"
                      :class="`${thumbnailIndex == 99 ? 'active' : ''}`"
                      class="relative item w-[80px] h-[80px] text-0 rounded-[6px] overflow-hidden cursor-pointer"
                      @click="onChangCover(99, mainImage, goods.mainVideo)"
                    >
                      <div
                        style="
                          background: rgb(0 0 0 / 30%);
                          border-radius: 100%;
                          border: 1px solid white;
                          top: 50%;
                          margin-top: -20px;
                          left: 50%;
                          margin-left: -20px;
                        "
                        class="absolute w-[40px] h-[40px] flex items-center justify-center"
                      >
                        <n-icon class="text-[24px] text-[#fff]">
                          <Play></Play>
                        </n-icon>
                      </div>
                      <img class="w-full h-full object" :src="mainImage" />
                    </div>
                    <div
                      class="w-[80px] item h-[80px] text-0 rounded-[6px] overflow-hidden cursor-pointer"
                      v-for="(item, i) in goods.productImage?.images"
                      :key="item"
                      :class="`${i == thumbnailIndex ? 'active' : ''}`"
                      @click="onChangCover(i, item)"
                    >
                      <img class="w-full h-full object" :src="item" />
                    </div>
                  </n-carousel>
                </div>
              </div>
            </div>
          </div>
          <div class="flex-1 w-0">
            <template v-if="goodsLoading">
              <n-skeleton text :repeat="8" />
              <n-skeleton text width="80%" :repeat="7" />
              <n-skeleton text width="60%" :repeat="8" />
              <div class="flex">
                <div class="w-[288px]">
                  <n-skeleton text width="100%" :sharp="false" height="40px" />
                </div>
                <div class="flex-1"></div>
                <div class="w-[288px]">
                  <n-skeleton text width="100%" :sharp="false" height="40px" />
                </div>
              </div>
            </template>
            <template v-else>
              <!-- 区间价 quoteType等于0和2才有区间价-->
              <template v-if="goods?.productSaleInfo.quoteType != 1">
                <div class="text-[18px] font-[500] text-[#1A1A1A] flex">
                  <div class="flex-1">{{ $t("common.价格说明") }}</div>
                </div>
                <div
                  class="my-[16px] bg-[#FFFBF6] flex rounded-[4px] p-[8px]"
                  v-if="goods.productSaleInfo"
                >
                  <div
                    class="w-[120px] text-[#5C5C5C] font-[300] text-[16px] leading-[28px]"
                  >
                    <div>{{ $t("common.单价") }}（CNY）</div>
                    <div class="mt-[32px]">{{ $t("common.单价") }}（MXN）</div>
                    <div class="mt-[32px]">{{ $t("common.最小订购量") }}</div>
                  </div>
                  <div
                    class="w-[120px] text-[#303030] text-[18px] text-center"
                    v-for="(item, i) in goods.productSaleInfo.priceRangeList"
                  >
                    <div class="flex">
                      <money class="m-auto" :money="item.price"></money>
                    </div>
                    <div class="mt-[32px] flex">
                      <money class="m-auto" :money="item.price" :isCny="false"></money>
                    </div>
                    <div class="mt-[32px] flex">
                      <div class="flex items-center m-auto">
                        <span>{{ item.startQuantity }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
              <!-- 区间价 -->

              <div class="">
                <div v-for="(type, i) in attrTypeData" :key="i" class="mb-[16px]">
                  <div class="text-[18px] font-[500] flex text-[#1A1A1A]">
                    <div>
                      {{ type.attributeNameTrans }}
                    </div>
                    <div
                      v-if="i == 0"
                      class="pl-[16px] flex-1 text-[18px] text-[#F3911A] font-[400]"
                    >
                      {{ currentSku.valueTrans }}
                    </div>
                    <div
                      v-if="i == attrTypeData.length - 1 || attrTypeData.length == 0"
                      class="text-right pl-[16px] pr-[8px] flex-1 text-[18px] text-[#767676] font-[300]"
                    >
                      {{ $t("common.最小订购量") }}：
                      {{ computedMinCount() }}
                    </div>
                  </div>
                  <div
                    v-if="i == 0 && attrTypeData.length > 1 && attrData"
                    class="flex flex-wrap mt-[8px] gap-[20px]"
                  >
                    <n-badge
                      :value="computedSkuQuantity(sku)"
                      v-for="sku in attrData.filter(
                        (x) => x.attributeId == type.attributeId
                      )"
                      :key="sku.skuId"
                    >
                      <div
                        v-if="sku.skuImageUrl"
                        class="sku rounded-[6px] overflow-hidden text-0 w-[72px] h-[72px] bg-[#fff] cursor-pointer text-center"
                        :class="currentSku.value == sku.value ? 'current' : ''"
                        @click="onClickSku(sku)"
                      >
                        <img
                          class="w-[72px] h-[72px] object-contain"
                          :alt="sku.valueTrans"
                          :title="sku.valueTrans"
                          :src="sku.skuImageUrl"
                        />
                      </div>
                      <div
                        v-else
                        class="sku rounded-[6px] overflow-hidden text-0 p-[4px] bg-[#fff] cursor-pointer text-center"
                        :class="currentSku.value == sku.value ? 'current' : ''"
                        @click="onClickSku(sku)"
                      >
                        {{ sku.valueTrans }}
                      </div>
                    </n-badge>
                  </div>
                  <div
                    v-else-if="currentSku.value || attrTypeData.length == 1"
                    class="sku-wrapper mt-[16px] bg-[#FFFBF6] flex flex-col gap-[20px] rounded-[8px] py-[20px] px-[8px] relative"
                  >
                    <div
                      class="flex gap-[10px] items-center text-[16px] font-[400] text-[#FDB231]"
                    >
                      <div class="flex-1">{{ $t("common.规格") }}</div>
                      <div class="w-[100px] text-right">{{ $t("common.单价") }}(CNY)</div>
                      <div class="w-[100px] text-right">{{ $t("common.单价") }}(MXN)</div>
                      <div class="w-[120px] text-right mr-[8px]">
                        {{ $t("common.库存") }}
                      </div>
                      <div class="w-[120px] text-center">{{ $t("common.数量") }}</div>
                    </div>
                    <div
                      ref="skuRef"
                      :class="skuHidden == true ? 'max-h-[580px]' : ''"
                      class="flex flex-col overflow-hidden"
                    >
                      <div
                        v-for="sku in currentSku.value
                          ? goods.productSkuInfos.filter((x) =>
                              x.skuAttributes.find((y) => y.value == currentSku.value)
                            )
                          : goods.productSkuInfos"
                        :key="sku.skuId"
                        class=""
                      >
                        <div
                          class="flex gap-[10px] items-center text-[16px] font-[300] text-[#5C5C5C]"
                        >
                          <div class="flex-1 text-[#303030] font-[400]">
                            {{
                              sku.skuAttributes[attrTypeData.length > 1 ? 1 : 0]
                                .valueTrans
                            }}
                          </div>
                          <div
                            class="w-[100px] text-[#303030] font-[400] flex justify-end"
                          >
                            <money
                              :moneyStyle="{ fontSize: '16px' }"
                              :money="computedSkuPrice(sku)"
                            ></money>
                          </div>
                          <div
                            class="w-[100px] text-[#303030] font-[400] flex justify-end"
                          >
                            <money
                              :moneyStyle="{ fontSize: '16px' }"
                              :money="computedSkuPrice(sku)"
                              :isCny="false"
                            ></money>
                          </div>
                          <div class="w-[120px] text-[#767676] text-right mr-[8px]">
                            {{ formatMoney(sku.amountOnSale, 0) }}
                          </div>
                          <div class="w-[120px] text-center">
                            <n-input-number
                              size="small"
                              v-model:value="sku.quantity"
                              :min="0"
                              :max="sku.amountOnSale"
                              :step="goods.batchNumber > 1 ? goods.batchNumber : 1"
                              placeholder=""
                              button-placement="both"
                              @update:value="onChangeQuantity(sku)"
                              @blur="onBlurQuantity(sku)"
                              :status="computedSkuCountError(sku) > 0 ? 'error' : ''"
                            />
                          </div>
                        </div>

                        <div class="text-right text-[--main-color] h-[20px]">
                          <template v-if="computedSkuCountError(sku) == 1">
                            {{ $t("common.最小订购量") }}：
                            {{ computedMinCount() }}
                          </template>
                          <template v-else-if="computedSkuCountError(sku) == 2">
                            Debería ser múltiplo de {{ goods.batchNumber }}.
                          </template>
                        </div>
                      </div>
                    </div>
                    <div
                      class="flex text-[--main-color]"
                      v-if="skuRef?.length > 0 && skuRef[0].offsetHeight >= 580"
                    >
                      <div
                        @click="skuHidden = !skuHidden"
                        class="flex items-center gap-2 m-auto cursor-pointer"
                      >
                        <n-icon>
                          <CaretDown v-if="skuHidden"></CaretDown>
                          <CaretUp v-else></CaretUp>
                        </n-icon>
                        <span>
                          {{ skuHidden ? $t("rightFloat.显示") : $t("rightFloat.隐藏") }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="mb-[32px]">
                  <!-- <div class="flex items-center">
                    <div class="flex-1 w-0 text-[18px] font-[500] text-[#1A1A1A]">
                      Select Shipping Address
                    </div>
                    <div
                      class="flex items-center text-[18px] font-[300] text-[--main-color]"
                    >
                      <div class="mr-[8px]">
                        <n-icon>
                          <Location></Location>
                        </n-icon>
                      </div>
                      <div class="">Zora，MEXICO, D.F.</div>
                    </div>
                  </div>
                  <div class="flex items-center mt-[16px]">
                    <div class="flex-1 w-0 text-[18px] font-[500] text-[#1A1A1A]">
                      Shipping-Related Fee
                    </div>
                    <div class="flex items-center text-[18px] font-[300] text-[#303030]">
                      <div class="mr-[8px]"></div>
                      <div class="">
                        <money :money="computedTotalAmount()" :isCny="false"></money>
                      </div>
                    </div>
                  </div> -->
                  <!-- <div class="mt-[16px] bg-[#FFFBF6] p-[10px]">
                    报价类型{{ goods.productSaleInfo.quoteType }}，起批量{{
                      goods.minOrderQuantity
                    }}，混批{{ goods.sellerMixSetting || "不支持混批" }}，已选{{
                      computedTotalQuantity()
                    }}，金额{{ computedTotalAmount() }}
                  </div> -->

                  <div
                    v-if="noSku"
                    class="text-[18px] font-[300] text-[--main-color] pt-[20px]"
                  >
                    {{ $t("tips.无法购买") }}
                  </div>
                  <div v-else class="flex items-center mt-[16px] pb-2">
                    <div class="relative flex-1">
                      <n-button
                        class="!w-[288px]"
                        type="primary"
                        block
                        size="large"
                        @click="onClickBuyNow"
                      >
                        {{ $t("button.现在购买") }}
                      </n-button>
                      <div
                        v-if="showCountError1"
                        class="absolute bottom-[-24px] text-[--main-color]"
                      >
                        La cantidad no puede ser 0
                      </div>
                    </div>
                    <!-- <div class="flex-1 w-0 text-[18px]"></div> -->
                    <div class="relative flex justify-end flex-1">
                      <n-button
                        class="!w-[288px]"
                        type="primary"
                        block
                        ghost
                        size="large"
                        @click="onClickAddToCart(false)"
                      >
                        {{ $t("button.加入购物车") }}
                      </n-button>
                      <div
                        v-if="showCountError2"
                        class="absolute bottom-[-24px] text-[--main-color]"
                      >
                        La cantidad no puede ser 0
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="!goodsLoading"
      class="bg-[#fff] mt-[24px] overflow-hidden"
      ref="attrContainerRef"
    >
      <div class="m-auto w attr-wrapper" :style="{ height: containerHeight }">
        <div class="bg-[#fff] py-[24px]" style="column-count: 3; column-gap: 1em">
          <div class="gap-[8px] mb-[8px]" style="break-inside: avoid">
            <div class="text-[#989898] text-[16px] text-left">
              {{ $t("title.店铺") }}
            </div>
            <div
              class="text-[--main-color] text-[16px] text-left cursor-pointer"
              @click="router.push(`/store/${goods.sellerOpenId}`)"
            >
              {{ $t("button.进入店铺") }}
              <!-- {{ goods.sellerOpenId }} -->
            </div>
          </div>

          <div
            class="gap-[8px] mb-[8px]"
            style="break-inside: avoid"
            v-for="item in groupedAttributesData"
            :key="item.attributeId"
          >
            <div class="text-[#989898] text-[16px] text-left">
              {{ item.attributeNameTrans }}
            </div>
            <div
              class="text-[#1A1A1A] text-[16px] text-left"
              style="overflow-wrap: anywhere"
            >
              {{ item.valueTrans }}
            </div>
          </div>
        </div>

        <div class="flex toggle-wrapper">
          <div
            @click="toggleAttr"
            class="flex items-center gap-2 m-auto cursor-pointer text-[14px] font-[400]"
          >
            <n-icon>
              <CaretDown v-if="!showAttr"></CaretDown>
              <CaretUp v-else></CaretUp>
            </n-icon>
            <span class="">
              {{ showAttr ? $t("rightFloat.隐藏") : $t("rightFloat.显示") }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="bg-[#fff]" v-if="goods.description">
      <div class="m-auto w">
        <div class="mt-[24px] flex text-center bg-[#fff] py-[24px]">
          <div v-if="!noSku" class="m-auto des-wrapper" v-html="goods.description"></div>
          <div v-else>
            <div class="w m-auto mt-[24px] grid grid-cols-5 gap-4">
              <div class="flex-1" v-for="item in recommendList" :key="item.offerId">
                <goodsCard :goods="item"></goodsCard>
              </div>
            </div>
            <div class="text-center mt-[32px]">
              <n-button type="primary" ghost @click="onClickRecommend">
                {{ $t("button.查看类似商品") }}
              </n-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <messageDialog ref="messageDialogRef" :width="600">
      <div>
        <div class="py-4 text-center">
          <img class="w-[100px] m-auto" src="/images/icons/6@1x.png" />
        </div>
        <div class="text-center text-[18px]">
          <div class="text-[--main-color] font-[400] mt-[16px]">
            ¡Producto agregado al carrito exitosamente!
          </div>
          <!-- <div class="">加入购物车成功</div> -->
        </div>
        <div class="flex justify-center my-[32px] gap-8">
          <n-button type="primary" class="w-[200px]" @click="router.push('/cart')">
            {{ $t("button.现在购买") }}
          </n-button>
          <n-button
            type="primary"
            ghost
            class="w-[200px]"
            @click="messageDialogRef.close()"
          >
            {{ $t("button.继续购物") }}
          </n-button>
        </div>
      </div>
    </messageDialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ImageSearchAlt } from "@vicons/carbon";
import { CaretDown, CaretUp, Play } from "@vicons/ionicons5";
import { getCommodityDetail, recommendSearch } from "@/api/product";
import { batchUpdate, batchDelete, getShoppingCartItemsByOfferId } from "@/api/cart";
import money from "@/components/money";
import { useMessage } from "naive-ui";
import { useI18n } from "vue-i18n";
import { useUser } from "@/stores/user";
import bus from "@/utils/mitt";
import goodsCard from "@/components/goodsCard.vue";
import { formatMoney } from "@/utils/formatMoney";
import messageDialog from "@/components/messageDialog.vue";
import { imageUrlSearch } from "@/utils/common";
const { setSettlementGoods } = useUser();
const { t } = useI18n();
const message = useMessage();
const containerRef = ref(null);
const attrContainerRef = ref(null);
const route = useRoute();
const router = useRouter();
const goodsId = route.params.id;
const goods = ref({});
const noSku = ref(false); //没有sku
//当前显示的主图
const cover = ref("");
const mainImage = ref("");
const currentSku = ref({});
const attrData = ref([]);
const attrTypeData = ref([]);
const groupedAttributesData = ref([]);
const showAttr = ref(false);
const containerHeight = ref("164px");
const goodsLoading = ref(true);
const recommendList = ref([]);
const skuRef = ref(null);
const skuHidden = ref(true);
const videoUrl = ref("");
const showCountError1 = ref(false);
const showCountError2 = ref(false);
const messageDialogRef = ref();
const uploading = ref(false);
/**
 * 展示/隐藏商品属性
 */
const toggleAttr = () => {
  showAttr.value = !showAttr.value;
  nextTick(() => {
    const height = showAttr.value
      ? attrContainerRef.value.scrollHeight + 60 + "px"
      : "164px";
    containerHeight.value = height;
  });
};

/**
 * 选中sku
 * @param {*} sku
 */
const onClickSku = (sku, keepVideo) => {
  currentSku.value = sku;
  if (sku.skuImageUrl) {
    cover.value = sku.skuImageUrl;
    if (!keepVideo) videoUrl.value = "";
  }
};

/**
 * 加载商品信息
 * @param {*} id
 */
const getGoods = async (id) => {
  goodsLoading.value = true;
  const { data } = await getCommodityDetail(id);
  goods.value = data.data;
  videoUrl.value = goods.value.mainVideo;
  goodsLoading.value = false;
  let uniqueAttributesTypes = [];
  let uniqueAttributes = [];
  let attributeTypeSet = new Set();
  let attributeSet = new Set();
  // 提取规格类型和规格
  if (goods.value.productSkuInfos?.length > 0 && !goods.value.isDisabled) {
    goods.value.productSkuInfos?.forEach((skuInfo) => {
      skuInfo.quantity = 0;
      skuInfo.skuAttributes.forEach((attr) => {
        // 提取规格类型
        let attrTypeKey = `${attr.attributeId}_${attr.attributeName}_${attr.attributeNameTrans}`;
        if (!attributeTypeSet.has(attrTypeKey)) {
          attributeTypeSet.add(attrTypeKey);
          uniqueAttributesTypes.push({
            attributeId: attr.attributeId,
            attributeName: attr.attributeName,
            attributeNameTrans: attr.attributeNameTrans,
          });
        }

        // 提取规格
        let attrKey = `${attr.attributeId}_${attr.value}_${attr.valueTrans}`;
        if (!attributeSet.has(attrKey)) {
          attributeSet.add(attrKey);
          uniqueAttributes.push({
            attributeId: attr.attributeId,
            value: attr.value,
            valueTrans: attr.valueTrans,
            skuId: attr.skuId,
            // 这里假定每个属性都有skuImageUrl，如果没有需要判断一下
            skuImageUrl: attr.skuImageUrl || null,
          });
        }
      });
    });
  } else {
    noSku.value = true;
    const { data: recommendData } = await recommendSearch({
      offerId: goods.value.offerId,
      pageNo: 1,
      pageSize: 10,
      language: "es",
    });
    recommendList.value = recommendData.data;

    // //没有规格
    // uniqueAttributesTypes.push({
    //   attributeId: goods.value.offerId,
    //   attributeName: "",
    //   attributeNameTrans: "",
    // });

    // uniqueAttributes.push({
    //   attributeId: goods.value.offerId,
    //   value: "Sin especificaciones",
    //   valueTrans: "Sin especificaciones",
    //   skuId: goods.value.offerId,
    //   specId: goods.value.offerId,
    //   skuImageUrl: null,
    //   quantity: 0,
    //   amountOnSale: goods.value.productSaleInfo.amountOnSale,
    // });
  }
  attrTypeData.value = uniqueAttributesTypes;
  attrData.value = uniqueAttributes;
  // console.log("规格类型:", uniqueAttributesTypes);
  // console.log("规格:", uniqueAttributes);

  //提取商品属性
  // 使用Map根据attributeName进行分组
  const groupedAttributes = new Map();
  const result = [];
  goods.value.productAttribute.forEach((item) => {
    const key = item.attributeId + item.attributeName; // 将attributeId和attributeName组合成唯一键
    if (!groupedAttributes.has(key)) {
      groupedAttributes.set(key, {
        attributeId: item.attributeId,
        attributeName: item.attributeName,
        value: item.value,
        attributeNameTrans: item.attributeNameTrans,
        valueTrans: item.valueTrans,
      });
    } else {
      const existingItem = groupedAttributes.get(key);
      // 使用斜线"/"拼接value和valueTrans
      existingItem.value += "/" + item.value;
      existingItem.valueTrans += "/" + item.valueTrans;
    }
  });

  // 将map中的值转换成数组
  groupedAttributes.forEach((value) => result.push(value));
  groupedAttributesData.value = result;

  if (attrTypeData.value.length > 1) {
    //多个属性  默认选中第一个
    onClickSku(attrData.value[0], true);
  }

  let _img = goods.value.productImage.whiteImage || goods.value.productImage.images[0];
  mainImage.value = _img;
  cover.value = _img;

  getShoppingCartItemsByOfferIdHandler();
};
getGoods(goodsId);

/**
 * 计算当前规格选择的数量
 * @param {*} sku
 */
const computedSkuQuantity = (sku, isTotal) => {
  let array = isTotal
    ? goods.value.productSkuInfos
    : goods.value.productSkuInfos.filter(
        (x) => x.skuAttributes.find((y) => y.value == sku.value) //用中文匹配防止重名
      );
  const sum = array.reduce((accumulator, currentValue) => {
    return accumulator + currentValue.quantity;
  }, 0);
  return sum;
};

/**
 * sku数量改变事件  调整单价
 * @param {*} sku
 */
const onChangeQuantity = async (sku) => {
  if (sku.quantity <= 0) {
    //触发删除
    await batchDelete(goods.value.productSkuInfos);
  }
  showCountError1.value = false;
  showCountError2.value = false;
};
const onBlurQuantity = (sku) => {
  let min = computedMinCount();
  //1手起批量
  let batchNumber = goods.value.batchNumber > 0 ? goods.value.batchNumber : 1;
  if (sku.quantity != 0) {
    const remainder = sku.quantity % batchNumber;
    if (remainder !== 0) {
      // 如果有余数，那么增加 (batchNumber - 余数)，使得总数可以被 batchNumber 整除
      sku.quantity += batchNumber - remainder;
    } else if (sku.quantity < min) {
      sku.quantity = min;
      // message.warning(`Este producto se debe comprar en un mínimo de ${min} piezas.`);
    }
  }
};

const computedSkuCountError = (sku) => {
  if (sku.quantity > 0) {
    if (sku.quantity < computedMinCount()) return 1;
    if (goods.value.batchNumber > 0 && sku.quantity % goods.value.batchNumber != 0) {
      return 2;
    }
  }
  return 0;
};
const computedTotalAmount = () => {
  //所有数量大于1的sku
  const skus = goods.value?.productSkuInfos?.filter((x) => x.quantity > 0);
  const sum = skus?.reduce((accumulator, currentValue) => {
    return accumulator + currentValue.quantity * computedSkuPrice(currentValue); //currentValue.consignPrice;
  }, 0);
  return sum;
};

const computedSkuPrice = (sku) => {
  // console.log("%c Line:427 🍔 sku", "color:#fca650", sku);
  // 0-无sku按商品数量报价，
  // 1-按sku规格报价
  // 2-有sku按商品数量报价

  const type = goods.value?.productSaleInfo.quoteType;
  if (type == 1) {
    return sku.price || sku.consignPrice; //优先使用批发价，没有则显示一件代发价
  } else {
    // console.log("%c Line:694 🍖", "color:#e41a6a");
    let range = goods.value?.productSaleInfo.priceRangeList;

    let quantity =
      type == 2 ? computedSkuQuantity(sku.skuAttributes[0], true) : sku.quantity; //sku合并统计数量

    if (quantity < computedMinCount()) {
      //小于起批量
      return range[0].price;
    }
    for (let i = range.length - 1; i >= 0; i--) {
      if (quantity >= range[i].startQuantity) {
        return range[i].price;
      }
    }
  }
};

const computedTotalQuantity = () => {
  //满足最小起批量的sku
  const skus = goods.value?.productSkuInfos?.filter(
    (x) => x.quantity >= computedMinCount()
  );
  //总数量
  const totalQuantity = skus?.reduce((accumulator, currentValue) => {
    return accumulator + currentValue.quantity;
  }, 0);
  return totalQuantity;
};

const computedCanBuy = () => {
  // const totalQuantity = computedTotalQuantity();
  // //混批  达到最小金额或者最小数量都允许购买
  // if (goods.value.sellerMixSetting && goods.value.sellerMixSetting.generalHunpi) {
  //   return (
  //     totalQuantity >= goods.value.sellerMixSetting.mixNumber ||
  //     computedTotalAmount() >= goods.value.sellerMixSetting.mixAmount
  //   );
  // } else {
  //   return totalQuantity >= goods.value.minOrderQuantity;
  // }

  // return totalQuantity;

  //混批判断 移到购物车或者订单确认界面   混批是指店铺内商品

  let skus = [];
  if (goods.value?.productSkuInfos) {
    skus = goods.value?.productSkuInfos?.filter((x) => x.quantity >= computedMinCount());
    if (!skus?.length) {
      // message.error("Por favor, indica la cantidad de compra.");

      return false;
    }
  } else {
    return false;
  }

  return true;
};

const onClickAddToCart = async (hideMessage) => {
  let skus = [];
  if (goods.value?.productSkuInfos) {
    skus = goods.value?.productSkuInfos?.filter((x) => x.quantity >= computedMinCount());
    if (!skus?.length) {
      // message.error("Por favor, indica la cantidad de compra.");
      if (hideMessage) showCountError1.value = true;
      else showCountError2.value = true;
      return;
    }
  } else {
    //没有规格
    skus = attrData.value;
  }

  showCountError2.value = false;
  const postData = skus.map((x) => {
    let img = "";
    if (x.skuAttributes?.length > 0) {
      img = x.skuAttributes[0].skuImageUrl;
    }
    return {
      offerId: goods.value.offerId,
      quantity: x.quantity,
      subject: goods.value.subjectTrans,
      whiteImage:
        img || goods.value.productImage.whiteImage || goods.value.productImage.images[0],
      specId: x.specId,
      supplierId: goods.value.sellerOpenId,
      openOfferId: "",
      price: computedSkuPrice(x),
      specInfo: JSON.stringify(x.skuAttributes),
      categoryId: goods.value.categoryId,
    };
  });
  const { data } = await batchUpdate(postData);
  bus.emit("onUpdateCart");
  // console.log("%c Line:652 🥒 hideMessage", "color:#2eafb0", hideMessage);
  if (!hideMessage) {
    // console.log("%c Line:653 🍯", "color:#f5ce50", data.data);
    if (data.data) {
      // message.success(t("tips.加购成功"));

      messageDialogRef.value.show();
    } else {
      message.error(t("tips.加购失败"));
    }
  }
};

const getShoppingCartItemsByOfferIdHandler = async () => {
  const { data } = await getShoppingCartItemsByOfferId(goods.value.offerId);
  if (data.data?.length > 0) {
    for (let i = 0; i < data.data.length; i++) {
      const element = data.data[i];
      let sku = goods.value?.productSkuInfos
        ? goods.value?.productSkuInfos?.find((x) => x.specId == element.specId)
        : attrData.value.find((x) => x.specId == element.specId);
      sku.quantity = element.quantity;
    }
  }
};

const onClickBuyNow = async () => {
  await onClickAddToCart(true);
  const { data } = await getShoppingCartItemsByOfferId(goods.value.offerId);
  if (!data.data.length) {
    // message.warning(
    //   "Por favor, selecciona los productos que necesitas pagar desde el carrito de compras."
    // );
    showCountError1.value = true;
    return;
  }
  setSettlementGoods(data.data);
  router.push("/submitOrder");
};

const onClickRecommend = async () => {
  router.push(`/recommend/${goods.value.offerId}`);
};

const thumbnailIndex = ref(null);
const onChangCover = (index, image, video) => {
  console.log("%c Line:870 🍞 index", "color:#ea7e5c", index);
  thumbnailIndex.value = index;
  cover.value = image;
  videoUrl.value = video ? video : "";
};

const computedMinCount = () => {
  if (goods.value?.productSaleInfo.quoteType == 1) {
    return goods.value?.minOrderQuantity;
  } else {
    if (goods.value?.productSaleInfo.priceRangeList.length > 0) {
      return goods.value?.productSaleInfo.priceRangeList[0].startQuantity;
    }
  }
};

const onClickSimilar = async () => {
  uploading.value = true;
  await imageUrlSearch(cover.value);
  uploading.value = false;
};
</script>

<style lang="scss" scoped>
.arrow {
  background-color: #fff;
  height: 100%;
  display: flex;
  i {
    margin: auto;
  }
}

.sku {
  border: 1px solid #aaaaaa;

  &.current {
    border: 2px solid var(--main-color);
  }
}

.attr-wrapper {
  position: relative;
  transition: height 0.5s ease-in-out;
  .toggle-wrapper {
    position: absolute;
    bottom: 0;
    width: 100%;
    left: 0;
    text-align: center;
    background-image: linear-gradient(-180deg, rgba(255, 255, 255, 0) 0%, #fff 70%);
    padding-top: 50px;
    padding-bottom: 16px;

    color: var(--main-color);
    font-size: 18px;
    font-weight: 300;
  }
}

.sku-wrapper {
  ::v-deep(.n-input__input-el) {
    font-size: 16px;
  }
}
.thumbnail-wrapper {
  .item {
    &:hover {
      border: 1px solid var(--main-color);
    }
    &.active {
      border: 1px solid var(--main-color);
    }
  }
}
</style>
<style lang="scss">
.des-wrapper {
  img {
    max-width: 100%;
  }
}
</style>
